import 'package:flutter/material.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_record.dart';
import 'package:qunaimedical/models/consultation_record.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

class RecordsPage extends StatefulWidget {
  final String word;

  const RecordsPage({Key key, @required this.word}) : super(key: key);

  @override
  _RecordsPageState createState() => _RecordsPageState();
}

class _RecordsPageState extends State<RecordsPage> {
  List<ConsultationRecord> _items = [];

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.separated(
        itemBuilder: (c, i) {
          return ItemRecord(
            _items[i],
            onDelete: () => _delete(i),
          );
        },
        itemCount: _items.length,
        separatorBuilder: (BuildContext context, int index) => CustomDivider(),
      ),
    );
  }

  void _fetchData() async {
    var value = await XHttp.postJson(
        sprintf(Urls.RECORDS, [SPUtils.getUser().id, 1, 20]),
        {'word': widget.word});
    if (value != null) {
      MapResponse response = MapResponse.fromJson(value);
      if (response.code == 1) {
        setState(() {
          _items = (response.data['records'] as List)
              .map((e) =>
                  ConsultationRecord.fromJson((e as Map<String, dynamic>)))
              .toList();
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _delete(int index) async {
    DialogUtils.showAlertDialog(context, '提示', '确认删除？', onPressed: () async {
      Navigator.pop(context);
      DialogUtils.showWaitDialog(context);
      var data =
          await XHttp.delete(sprintf(Urls.RECORD_DELETE, [_items[index].id]));
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          setState(() {
            _items.removeAt(index);
          });
        }
      }
    });
  }
}
